#!/usr/bin/python3

import serial
import time

# List possible USB serial devices
def list_serial_ports():
    import subprocess
    result = subprocess.run(['ls', '/dev/ttyUSB*', '/dev/ttyACM*'], 
                           capture_output=True, text=True)
    return result.stdout.strip().split('\n')

# Try to automatically find ESP32 serial port
def find_esp32_port():
    ports = list_serial_ports()
    if not ports or ports[0] == '':
        print("No USB serial devices found. Please check ESP32 connection.")
        return None
    
    print(f"Found serial devices: {', '.join(ports)}")
    return ports[0]  # Usually use the first device

def read_esp32_serial(port='/dev/ttyUSB0', baudrate=115200):
    if port is None:
        port = find_esp32_port()
        if port is None:
            return
    
    print(f"Connecting to {port}, baudrate: {baudrate}")
    
    try:
        # Open serial port
        ser = serial.Serial(port, baudrate, timeout=1)
        print("Serial connection successful. Reading data...")
        
        # Continuously read data
        while True:
            if ser.in_waiting > 0:
                line = ser.readline().decode('utf-8').rstrip()
                print(f"ESP32: {line}")
            time.sleep(0.1)  # Short sleep to reduce CPU usage
            
    except serial.SerialException as e:
        print(f"Serial error: {e}")
    except KeyboardInterrupt:
        print("Program exited")
    finally:
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("Serial port closed")

if __name__ == "__main__":
    read_esp32_serial()